<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        table {
            margin: 100px auto;
            text-align: center;
            border-collapse: collapse;
        }
        
        table,
        th,
        tr,
        td {
            border-bottom: 1px solid #ccc;
        }
        
        table td {
            width: 80px;
        }
        
        table,
        th {
            border-top: 1px solid #ccc;
        }
        
        table th {
            background-color: aquamarine;
        }
    </style>
</head>

<body>
    <div class="wrap">
        <table>
            <thead>
                <tr>
                    <th>
                        全选 <input type="checkbox" id="j_cbAll" />
                    </th>
                    <th>商品</th>
                    <th>价钱</th>
                </tr>
            </thead>
            <tbody class="j_tb">
                <tr>
                    <td>
                        <input type="checkbox" />
                    </td>
                    <td>小米</td>
                    <td>8888</td>
                </tr>
                <tr>
                    <td>
                        <input type="checkbox" />
                    </td>
                    <td>华为</td>
                    <td>7777</td>
                </tr>
                <tr>
                    <td>
                        <input type="checkbox" />
                    </td>
                    <td>三星</td>
                    <td>9999</td>
                </tr>
            </tbody>
        </table>
    </div>
    <script>
        //1.全选和取消全选的做法 让下面复选框的属性跟随全选按钮
        var j_cbAll = document.querySelector("#j_cbAll"); //全选按钮
        var j_tbs = document.querySelector(".j_tb").getElementsByTagName("input");
        j_cbAll.onclick = function() {
                //console.log(this.checked);
                for (var i = 0; i < j_tbs.length; i++) {
                    j_tbs[i].checked = this.checked;
                }
            }
            //2.下面复选框要全部都选中，上面的复选框才显示选中状态
        for (var i = 0; i < j_tbs.length; i++) {
            j_tbs[i].onclick = function() {
                flag = true; //控制全选按钮是否选中
                //每次点击都会循环检查下面四个复选框是否全部被选中
                for (var j = 0; j < j_tbs.length; j++) {
                    if (!j_tbs[j].checked) {
                        j_cbAll.checked = false;
                        break;
                    } else {
                        j_cbAll.checked = true;
                    }
                }
            }
        }
    </script>
</body>

</html>